package com.cater.sys.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cater.sys.entity.Filestorage;
import com.cater.sys.entity.Resource;
import com.cater.sys.entity.User;
import com.cater.sys.service.FilestorageService;
import com.cater.sys.service.ResourceService;
import com.cater.sys.service.RoleService;
import com.cater.sys.service.UserService;
import com.cater.utils.CaptchaUtil;
import com.cater.utils.MD5Util;

/**
 *
 * @描述:登录
 * @作者 :ShenDong
 * @创建日期 :2016年12月7日8:41
 *
 */
@Controller
@RequestMapping("/")
public class LoginController {

	@Autowired
	UserService userService;

	@Autowired
	ResourceService resourceService;

	@Autowired
	RoleService roleService;

	@Autowired
	private FilestorageService filestorageServiceImpl;// 文件上传

	private InputStream input = getClass().getClassLoader().getResourceAsStream("jdbc.properties");// 加载Java项目根路径下的配置文件
	private Properties properties = new Properties();

	/**
	 * 打开登录页面
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/login")
	public String login(Model model, HttpServletRequest request) throws IOException {
		model.addAttribute("bs", 0);
		properties.load(input);// 加载属性文件
		String projectName = properties.getProperty("projectName");
		request.getSession().setAttribute("siteName", projectName);
		return "sys/login";
	}

	/**
	 * @登录
	 * @作者 :ShenDong
	 * @创建日期 :2016年12月7日 上午12:23:00
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/logins")
	public Map<String, Object> logins(@Validated User user, String app, String code, HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		// shiro管理的session
		Subject subject = SecurityUtils.getSubject();
		/*if (!"true".equals(app)) {
			if (subject.isAuthenticated()) {
				modelMap.put("code", 444);
				modelMap.put("message", "该用户已登录！");
				return modelMap;
			}
		}*/
		Session session = subject.getSession();
		if (!"true".equals(app)) {// app免除验证码
			/*
			 * String sessionCode = (String) session.getAttribute(CaptchaUtil.KEY_CAPTCHA);
			 * // 获取session中的验证码 if (null == code || "".equals(code)) { modelMap.put("code",
			 * 999); modelMap.put("message", "验证码为空！"); return modelMap; } if
			 * (!code.equals(sessionCode)) { modelMap.put("code", 999);
			 * modelMap.put("message", "验证码错误！"); return modelMap; }
			 */
		}

		User users = null;
		if ("true".equals(app)) {
			// app方面,不需要再次MD5加密
			users = userService.findByNameandpwd(user.getUsername(), user.getPassword());
		} else {
			users = userService.findByNameandpwd(user.getUsername(), MD5Util.string2MD5(user.getPassword()));
		}

		if (users != null) {
			// session.setAttribute("user", users);
			session.removeAttribute(CaptchaUtil.KEY_CAPTCHA);

			// shiro加入身份验证
			Subject subjects = SecurityUtils.getSubject();
			UsernamePasswordToken token = null;
			if ("true".equals(app)) {
				// app方面,不需要再次MD5加密
				token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
				User user1 = userService.getByid(users.getId());
				String realPath = request.getSession().getServletContext().getRealPath("/") + "static/upload/";
				List<Filestorage> list = filestorageServiceImpl.getAllByattributeId(Long.valueOf(user1.getId()), 2);
				if (list != null && list.size() > 0) {
					Filestorage filestorage = filestorageServiceImpl.getById(String.valueOf(list.get(0).getFlieId()));
					if (filestorage != null) {
						user1.setUrl("/static/upload/" + filestorage.getFlieName());
					}
				}
				modelMap.put("obj", user1);
			} else {
				token = new UsernamePasswordToken(user.getUsername(), MD5Util.string2MD5(user.getPassword()));
			}
			/* try { */
			subjects.login(token);
			/*
			 * } catch (AuthenticationException e) { modelMap.put("code", 999);
			 * modelMap.put("message", "身份验证失败！"); return modelMap; }
			 */
		} else {
			modelMap.put("code", 999);
			modelMap.put("message", "用户名或密码错误！");
			return modelMap;
		}
		/* Assert.assertEquals(true, subject.isAuthenticated()); //断言用户已经登录 */
		modelMap.put("code", 200);
		modelMap.put("message", "登录成功！");
		return modelMap;
	}

	/**
	 *
	 * @描述:登录验证码
	 * @方法名称 :getImage
	 * @作者 :ShenDong
	 * @创建日期 :2016年12月7日 上午12:23:00
	 * @param request
	 * @param response
	 *
	 */
	@RequestMapping(value = "/getCaptcha")
	public void getImage(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("image/jpeg");
		// 不缓存此内容
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expire", 0);
		try {

			HttpSession session = request.getSession();

			CaptchaUtil tool = new CaptchaUtil();
			StringBuffer code = new StringBuffer();
			BufferedImage image = tool.genRandomCodeImage(code);
			session.removeAttribute(CaptchaUtil.KEY_CAPTCHA);
			session.setAttribute(CaptchaUtil.KEY_CAPTCHA, code.toString());

			// 将内存中的图片通过流动形式输出到客户端
			ImageIO.write(image, "JPEG", response.getOutputStream());

		} catch (Exception e) {
		}
	}

	/**
	 *
	 * @描述:跳转到index
	 * @方法名称 :getImage
	 * @作者 :ShenDong
	 * @创建日期 :2016年12月7日 上午12:23:00
	 * @param request
	 *
	 */
	@RequestMapping("/index")
	public ModelAndView index(ModelAndView mv, HttpServletRequest request) {
		HttpSession session = request.getSession(true);
		if (session.isNew()) {
			// session无效，在这里进行页面跳转，返回到登录页面
			mv.setViewName("sys/login");
		}
		User user = (User) request.getSession().getAttribute("user_in_session");
		if (user == null) {
			Subject subjects = SecurityUtils.getSubject();
			subjects.logout();
			mv.addObject("bs", 0);
			mv.setViewName("sys/login");
			return mv;
		}
		List<Resource> resourcep = resourceService.getAllbyroleIds(0, user.getId());
		List<Resource> menu = new ArrayList<Resource>();
		for (Resource resource2 : resourcep) {
			List<Resource> list = resourceService.getAllbyroleIds(resource2.getId(), user.getId());
			resource2.setChildren(list);
			menu.add(resource2);
		}
		mv.addObject("menu", menu);
		mv.setViewName("sys/index");
		return mv;
	}

	/**
	 * 进入tab标签
	 * 
	 * @return
	 */
	@RequestMapping(value = "/tab")
	public String tab() {
		return "sys/tab";
	}

	public void login(User user, HttpServletRequest request, HttpServletResponse response) {
		baseLogin(user, request, response);
	}

	public void baseLogin(User user, HttpServletRequest request, HttpServletResponse response) {

		try {
			Subject subject = SecurityUtils.getSubject();
			if (subject.isAuthenticated()) {
				return;
			}
			// 如果用户已登录，先踢出
			/* ShiroSecurityHelper.kickOutUser(user.getUsername()); */

			boolean rememberMe = ServletRequestUtils.getBooleanParameter(request, "rememberMe", false);
			UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword(), rememberMe);
			subject.login(token); // 登录
		} catch (Exception e) {
			// 做一些异常处理
		} finally {
			/*
			 * ShiroAuthorizationHelper.clearAuthorizationInfo(sessionUser. getUsername());
			 */
		}
	}

	/**
	 * 打开登录页面
	 * 
	 * @return
	 */
	@RequestMapping("/unauthorized")
	public String unauthorized() {
		return "sys/unauthorized";
	}

	/**
	 * 用户注销
	 * 
	 * @param session
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/logout")
	public ModelAndView logout(ModelAndView mv, Integer bs, HttpServletRequest request) throws IOException {

		// shiro管理的session
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();

		session.removeAttribute("user_in_session");
		session.removeAttribute("user");
		session.removeAttribute("deppid_in_session");
		session.removeAttribute("depflog_in_session");
		session.removeAttribute("dep_in_session");

		// shiro销毁登录
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		if (bs != null) {
			if (bs == 1) {
				mv.addObject("bs", bs);
			}
		} else {
			mv.addObject("bs", 0);
		}
		properties.load(input);// 加载属性文件
		String projectName = properties.getProperty("projectName");
		request.getSession().setAttribute("siteName", projectName);
		mv.setViewName("sys/login");
		return mv;
	}

	@ResponseBody
	@RequestMapping(value = "/logouts")
	public boolean logout(Integer bs) {
		// shiro管理的session
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		session.removeAttribute("user_in_session");
		session.removeAttribute("user");
		session.removeAttribute("deppid_in_session");
		session.removeAttribute("depflog_in_session");
		session.removeAttribute("dep_in_session");
		// shiro销毁登录
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return true;
	}

	@ResponseBody
	@RequestMapping("/sgetall")
	public List<Resource> getAll() {
		List<Resource> list = resourceService.getByUserIdZid(1, 1);
		List<Resource> lists = new ArrayList<Resource>();
		for (Resource resource : list) {
			int bs = 0;
			for (Resource resou : lists) {
				if (resou.getId().equals(resource.getId())) {
					bs = 1;
				}
			}
			if (bs == 0) {
				lists.add(resource);
			}
		}
		;
		return lists;
	}
}
